# -*- coding: utf-8 -*-


import asyncio
import random
import logging
import py_global

from asyncio import Semaphore

logger = logging.getLogger(__name__)


async def delay_semaphore(param: str, semaphore: Semaphore):
    async with semaphore:  # 使用上下文管理器
        delay: float = random.random() * 10
        logger.info(f'param:{param}, delay:{delay}, task start.')
        await asyncio.sleep(delay)
        logger.info(f'param:{param}, delay:{delay}, task end.')

    # 显示10秒钟之内能够运行的协程数量
    # await asyncio.sleep(10)


async def run_semaphore():
    # 使用Semaphore限制协程数量
    semaphore = Semaphore(3)
    futures = list()
    for i in range(10):
        future = asyncio.create_task(delay_semaphore(f'task-{i}', semaphore))
        futures.append(future)

    await asyncio.gather(*futures)


def run_main():
    asyncio.run(run_semaphore())


if __name__ == '__main__':
    run_main()
